package com.zcp.pcsuitall.business;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.channels.SocketChannel;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.LinkedList;

import org.xmlpull.v1.XmlSerializer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;
import android.util.Log;
import android.util.Xml;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.Item;
import com.zcp.pcsuitall.XmlDataDealWith;

public class CallLogManager implements IDealWithMessage {
	private SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private Date dateTime = new Date(0l);
	private Timestamp ts = new Timestamp(0l);

	@Override
	public boolean dealWith(SocketChannel sc, Action action, Context context) {
		boolean success = false;
		if (action != null) {
			String op = action.getName();
			if (op.equals("LoadCallLog")) {
				success = dealWithLoad(sc, action, context);
			}else if (op.equals("AddCalllog")) {
            	success=dealWithAdd(sc,action,context);   
            }else if(op.equals("CleanupCalllog")){
            	success = dealWithCleanup(sc, action, context);
            }else if(op.equals("DeleteCalllog")){
            	success = dealWithDelete(sc, action, context);
            } 
		}
		return success;
	}
	
	
	/**
     * 处理清空短信方法。
     */
    private boolean dealWithCleanup(SocketChannel sc, Action action,
			Context context) {
    	String type = XmlDataDealWith.getRegularSingle("type",action.getSource());
	    try {
	    	if(type.equals("")){
	    		BusinessControl.returnToClient(sc,XmlDataDealWith.getErrorString(action.getName(),"6", "action CleanupCalllog type is null"),context);
	    		return false;
	    	}else if(type.equals("0")){
	    		Log.v(TAG, "CleanupCalllog type is all");
	    		context.getContentResolver().delete(CallLog.Calls.CONTENT_URI, null,null);
	    		BusinessControl.returnToClient(sc, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>CleanupCalllog</action></root>",context);
	    		return true;
	    	}else{
	    		Log.v(TAG, "CleanupCalllog type is "+type);
	    		context.getContentResolver().delete(CallLog.Calls.CONTENT_URI, "type=?", new String[]{type});
	    		BusinessControl.returnToClient(sc, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>CleanupCalllog</action></root>",context);
	    		return true;
	    	}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
			BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
			return false;
		}
    }
    
    /**
     * 处理删除短信方法。
     */
    private boolean dealWithDelete(SocketChannel sc, Action action,
    		Context context) {
    	values=XmlDataDealWith.getData(new String[]{"id"}, action.getSource());
    	if(values.isEmpty()||values.get(0).getItemData("id")==null){
    		BusinessControl.returnToClient(sc,XmlDataDealWith.getErrorString(action.getName(),"6", "action deleteCalllog id is null"),context);
    		return false;
    	}
    	try {
	    	for(int i=0;i<values.size();i++){
	    		if(values.get(i).getItemData("id").equals("")){
	    			continue;
	    		}
	    		Log.v(TAG, "delete calllog id is "+values.get(i).getItemData("id"));
	    		context.getContentResolver().delete(CallLog.Calls.CONTENT_URI, "_id=?", new String[]{values.get(i).getItemData("id")});
	    	}
	    	values.clear();
	    	BusinessControl.returnToClient(sc, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>DeleteCalllog</action></root>",context);
    		return true;
    	} catch (Exception e) {
    		Log.e(TAG, e.getMessage());
    		e.printStackTrace();
    		BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
    		return false;
    	}
    }
    
	private String[] ADD_KEYS=
		    new String[] {
		            "id", "number", "duration", "type", "date"
		    };
		    
    private LinkedList<Item> values=null;
    private LinkedList<ContentValues> contentValueList = new LinkedList<ContentValues>();
    private Item item=null;

	private boolean dealWithAdd(SocketChannel sc, Action action, Context context) {
		
		values= XmlDataDealWith.getDataByXml(ADD_KEYS, action.getSource(), 3, 1);
    	
    	try{
    		
    		if(values.isEmpty()){
    			BusinessControl.returnToClient(sc,XmlDataDealWith.getErrorString(action.getName(),"6", "action AddCalllog values is empty"),context);
    		}else{
    			long beginTime = System.currentTimeMillis(); 
    			
    			ContentValues contentValue = null;
    			int size=values.size();
    			
    			item=null;
    			contentValueList.clear();
    			for(int i=0;i<size;i++){
    				item=values.get(i);
    				if(values.get(i).getItemData(DATE).equals("")&&item.getItemData("number").equals("")){
    					Log.v(TAG, "address and date is null");
    					continue;
    				}
    				contentValue = new ContentValues();
    				contentValue.put("number", item.getItemData("number"));
    				contentValue.put("duration", item.getItemData("duration"));
    				//把时间格式的字符串转换成系统需要的long类型插入数据库
    				contentValue.put(DATE, String.valueOf(ts.valueOf((item.getItemData(DATE))).getTime()));
    				contentValue.put("type", item.getItemData("type"));
    				contentValueList.add(contentValue);
    				item=null;
    			}
				context.getContentResolver().bulkInsert(CallLog.Calls.CONTENT_URI, contentValueList.toArray(new ContentValues[0]));
				
				 //计算运行时间值  
    			long endTime = System.currentTimeMillis();  
    			long period = endTime - beginTime;     			
    			BusinessControl.returnToClient(sc, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>AddCalllog</action></root>",context);
    			Log.v(TAG, String.valueOf(period/1000));
    		}
    	}catch(Exception e){
    		Log.e(TAG, e.getMessage());
    		e.printStackTrace();
    		BusinessControl.returnToClient(sc,XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()),context);
			return false;
    	}
    	values.clear();
    	contentValueList.clear();
    	return true;
	}

	/**
	 * 处理查询方法。
	 */
	private boolean dealWithLoad(SocketChannel sc, Action action,
			Context context) {

		try {
			String result = LoadCalllog(context, action);// 以字符形式的XML输出
			System.out.println(result);
			BusinessControl.returnToClient(sc, result, context);
			return true;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
			BusinessControl.returnToClient(
					sc,
					XmlDataDealWith.getSystemErrorString(action.getName(),
							e.toString()), context);
			return false;
		}
	}

	/**
	 * 查询。
	 * 
	 * @param context
	 * @return
	 */
	private String LoadCalllog(Context context, Action action) {
		Cursor c = null;
		System.out.println("////"+action.toString());
		int id = 0;
		long duration = 0l;
		long date = 0l;
		int type = 0;
		String number = "";

		String from_type = XmlDataDealWith.getRegularSingle("type",action.getSource());
		String from = XmlDataDealWith.getRegularSingle("from",action.getSource());
		String to = XmlDataDealWith.getRegularSingle("to",action.getSource());
		
		System.out.println(from+"///"+to+"///"+from_type);
		String where_clause = null;
		if(!from_type.equals("0")){
			where_clause = "type = "+from_type;
		}
		
		int calllog_from = Integer.valueOf(from).intValue();
		int calllog_to = Integer.valueOf(to).intValue();
		int calllog_count = getTotol(context);
		
		int limit = calllog_to-(calllog_from-1);
		int offset = calllog_from-1;
		
		StringWriter writer = new StringWriter();
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(writer);
			XmlDataDealWith.createPre(action, serializer);
			c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,null,where_clause, null,"_id ASC LIMIT "+limit+" OFFSET "+offset);

			boolean have = c.moveToFirst();
			if (have) {
				do {
					id = c.getInt(c.getColumnIndex("_id"));
					number = c.getString(c.getColumnIndex("number"));
					type = c.getInt(c.getColumnIndex("type"));
					duration = c.getInt(c.getColumnIndex("duration"));
					date = c.getLong(c.getColumnIndex("date"));
					dateTime.setTime(Long.parseLong(String.valueOf(date)));
					
					serializer.startTag(SPACE, ITEM);
					serializer.startTag(SPACE, ID);
					serializer.text(id+"");
					serializer.endTag(SPACE, ID);
					serializer.startTag(SPACE, NUMBER);
					serializer.text(number);
					serializer.endTag(SPACE, NUMBER);

					serializer.startTag(SPACE, DATE);
					serializer.text(dateFormat.format(dateTime));
					serializer.endTag(SPACE, DATE);

					serializer.startTag(SPACE, DURATION);
					serializer.text(duration+"");
					serializer.endTag(SPACE, DURATION);

					serializer.startTag(SPACE, TYPE);
					serializer.text(type+"");
					serializer.endTag(SPACE, TYPE);
					serializer.endTag(SPACE, ITEM);

				} while (c.moveToNext());
	    		
	    		if (calllog_from <= 0 || calllog_to <= 0 || calllog_to < calllog_from || calllog_from > calllog_count) {
	    			return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>LoadCalllog</action><data></data><from></from><to></to><total></total></root>";
	    		}
	    		
	    		serializer.endTag(SPACE, DATA);
	    		
	            if (calllog_count>0) {
	            	serializer.startTag(SPACE, FROM);
	                serializer.text(from);
	                serializer.endTag(SPACE, FROM);

	                serializer.startTag(SPACE, TO);
	                serializer.text(to);
	                serializer.endTag(SPACE, TO);

	                serializer.startTag(SPACE, TOTAL);
	                serializer.text(calllog_count+"");
	                serializer.endTag(SPACE, TOTAL);
	            }else{
	            	serializer.startTag(SPACE, FROM);
	                serializer.text(0+"");
	                serializer.endTag(SPACE, FROM);

	                serializer.startTag(SPACE, TO);
	                serializer.text(0+"");
	                serializer.endTag(SPACE, TO);

	                serializer.startTag(SPACE, TOTAL);
	                serializer.text(0+"");
	                serializer.endTag(SPACE, TOTAL);
	            }
	            
	            serializer.endTag(SPACE, ROOT);
	            serializer.endDocument();
			}
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return XmlDataDealWith.getSystemErrorString(action.getName(),
					e.toString());
		} finally {
			serializer = null;
			try {
				c.close();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			writer = null;
		}
	}
	
	public int getTotol(Context context){
    	Cursor c = null;
    	int total = 0;
		try{
			c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[]{"count(*) as calllog_count"}, null, null,null);
			c.moveToFirst();
			total = c.getInt(0);
		}catch (Exception e) {
            e.printStackTrace();
		}finally{
			c.close();
		}
		return total;
    }

	public static final int INCOMING_TYPE = 1;
	public static final int OUTGOING_TYPE = 2;
	public static final int MISSED_TYPE = 3;

	private String ID = "id";
	private String NUMBER = "number";
	private String DATE = "date";
	private String DURATION = "duration";
	private String TYPE = "type";

	private String SPACE = "";
	
	private String FROM = "from";

	private String TO = "to";

	private String TOTAL = "total";

	private String ITEM = "item";

	private String DATA = "data";

	private String ROOT = "root";

	private String NOSETTING = "notSetting";
	private static String TAG = "CalllogManager";
}
